#!/bin/bash
scriptWorkd=$(cd "$(dirname $0)";pwd)

### ========= 全局变量 ===========
program=${HOME}/bin
### ==============================

### ========= 前置文件 ===========
if [[ -f ${HOME}/bin/basic_func.sh ]];then  ### 存在才载入
    source ${HOME}/bin/basic_func.sh
elif [[ -f ${scriptWorkd}/../bin/basic_func.sh ]];then
    source ${scriptWorkd}/../bin/basic_func.sh
elif [[ -f ./bin/basic_func.sh ]];then
    source ./bin/basic_func.sh
fi
### ==============================

function installNode20() {
set -e
    last_dir=$(pwd)
    install_to=${program}/node-20.12

    echo -e "${blue}Unzipping${normal}"
    now_dir=$(pwd)
    mkdir -p ./temp
    cd ./temp
    ### curl -o node-v20.12.tar.xz https://nodejs.org/dist/v20.12.2/node-v20.12.2-linux-x64.tar.xz
    tar -xf ../sub_pkg/node-v20.12.2-linux-x64.tar.xz -C ./

    # mkdir -p ${install_to}
    echo -e "${blue}Copying${normal}"
    cd node-v20.12.2-linux-x64
    if ! [[ -d ${install_to} ]]; then
        mkdir -p ${install_to}
    fi
    cp -rR ./* ${install_to}

set +u
    ### 加入环境变量
    insert "### nodev20.12.2" ${HOME}/.envrc
    insert_env 'PATH' "${install_to}/bin" ${HOME}/.envrc
    insert_env "LIBRARY_PATH" "${install_to}/lib" ${HOME}/.envrc
    insert_env 'LD_LIBRARY_PATH' "${install_to}/lib" ${HOME}/.envrc
    insert_env 'C_INCLUDE_PATH' "${install_to}/lib" ${HOME}/.envrc
    insert_env 'CPP_INCLUDE_PATH' "${install_to}/lib" ${HOME}/.envrc
set +u
    source ${HOME}/.envrc

    cd "${now_dir}"
    # rm -r ./temp
    cd "${last_dir}"
    echo -e "${blue}Done nodev20.12.2${normal}"
    unset last_dir
    unset install_to
set +Eeu
}
function npmConfig() {
set -e
    source ${HOME}/.envrc
    npm config set registry https://registry.npmmirror.com/
    npm config get registry
    npm -g install yarn
set +e
    yarn global add tree-sitter-cli
    sed -i "s#https://github.com#https://gh-proxy.com/&#g" ${HOME}/.config/yarn/global/node_modules/tree-sitter-cli/install.js
    yarn global add ${HOME}/.config/yarn/global/node_modules/tree-sitter-cli
    # yarn global add tree-sitter
    yarn global add tree-sitter
    insert_env 'PATH' "${HOME}/.yarn/bin" ${HOME}/.envrc
    # npm -g install --verbose tree-sitter-cli
    # npm -g install --verbose tree-sitter
}

function main() {
set -e
    ## 开始信息
    echo -e "${blue4}\n$(basename $0)\n${normal}"

    installNode20
    npmConfig
    echo -e "${hintStrSucceed}\nNode20 installed\nNode20安装完成${normal}\n"

    ## 结束信息
    echo -e "${green4}\n$(basename $0)\n${normal}"
}
main $@
